package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.HouseTypeMapper;
import com.bwie.mapper.RoomStateMapper;
import com.bwie.pojo.HouseType;
import com.bwie.pojo.Room;
import com.bwie.pojo.RoomState;
import com.bwie.service.RoomService;
import com.bwie.mapper.RoomMapper;
import com.bwie.utils.R;
import com.bwie.vo.MessageVo;
import com.bwie.vo.PageInfoVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
* @author lenovo
* @description 针对表【t_room】的数据库操作Service实现
* @createDate 2024-09-25 09:13:38
*/
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room>
    implements RoomService{

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RoomStateMapper roomStateMapper;

    @Autowired
    private HouseTypeMapper houseTypeMapper;
    /**
     * @description:init
     * @author: sxting~😊
     * @Date: 2024/9/25 11:51
     * @return: com.bwie.utils.R
     **/

    @PostConstruct
    public void init(){
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                rabbitTemplate.convertAndSend(exchange,routingKey,message);
            }
        });
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(ack){
                    System.out.println("发送成功");
                }else{
                    System.out.println("发送失败");
                }
            }
        });

    }

    /**
     * @description:列表
     * @author: sxting~😊
     * @Date: 2024/9/25 11:51
     * @return: com.bwie.utils.R
     **/

    @Override
    public R roomList(PageInfoVo pageInfoVo) {

        Page<Room> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        QueryWrapper<Room> wrapper = new QueryWrapper<>();

        wrapper.orderByAsc("room_state_id","room_price");

        roomMapper.selectPage(page, wrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("list",page.getRecords());

        return R.OK(map);
    }
    /**
     * @description:添加
     * @author: sxting~😊
     * @Date: 2024/9/25 11:51
     * @return: com.bwie.utils.R
    **/

    @Override
    @Transactional
    public R addRoom(Room room) {

        RoomState roomState = roomStateMapper.selectById(room.getRoomStateId());

        room.setRoomStateName(roomState.getRoomStateName());

        HouseType houseType = houseTypeMapper.selectById(room.getHouseTypeId());

        room.setHouseTypeName(houseType.getHouseTypeName());

        int i = roomMapper.insert(room);

        MessageVo messageVo = new MessageVo();
        messageVo.setMsgId(UUID.randomUUID().toString());
        messageVo.setMsgBody(room.getRoomNum().toString());

        redisTemplate.opsForValue().set("msg:"+messageVo.getMsgId(),messageVo.getMsgBody());

        rabbitTemplate.convertAndSend("directExchange","roomBinding",JSON.toJSONString(messageVo));

        return R.OK(i);
    }

    /**
     * @description:roomQueue
     * @author: sxting~😊
     * @Date: 2024/9/25 11:50
     * @param:
     * @param message
     * @param channel
     * @return: void
    **/
    @RabbitListener(queues = "roomQueue")
    public void goodsQueue(Message message, Channel channel){
        try {
            String s = new String(message.getBody());
            MessageVo messageVo = JSON.parseObject(s, MessageVo.class);
            String msgId = messageVo.getMsgId();
            String msgBody = messageVo.getMsgBody();

            if(redisTemplate.hasKey(msgId)){
                /*System.out.println("消费失败");*/
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            }

            System.out.println("消息内容："+msgBody);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            redisTemplate.delete(msgId);

        } catch (IOException e)  {
            throw new RuntimeException(e);
        }
    }
}




